<template>
  <el-row>
    <el-col :span="24">
      <div class="grid-content">
        <label>选择评价时间</label>
        <el-select v-model="selectDate" placeholder="选择评价时间" size="large" style="width: 240px" @change="handleChange">
          <el-option v-for="item in evaluate_time" :key="item.value" :label="item.label" :value="item.label" />
        </el-select>
      </div>
    </el-col>
    <el-col :span="24" v-if="infoType == 0">
      <div style="margin-left: 20px;">
        <el-button type="primary" @click="addComment">新增评价</el-button>
      </div>
    </el-col>
    <el-col :span="24" style="width: 100%;">
      <div class="grid-content">
        <el-table :data="spareComment" style="width: 100%">
          <el-table-column fixed prop="studentid" label="学号" width="120" align="center" />
          <el-table-column prop="commentTime" label="评价学年" width="150" align="center" />
          <el-table-column prop="comment" label="评价信息" width="300" align="center" show-overflow-tooltip />
          <el-table-column prop="statue" label="学生查看状态" width="120" align="center">
            <template #default="{ row }">
              <el-tag v-if="row.statue == 1" type="success">已读</el-tag>
              <el-tag v-else type="error">未读</el-tag>
            </template>
          </el-table-column>
          <!-- 使用 v-slot 语法来处理作用域插槽 -->
          <el-table-column prop="operate" label="操作" align="center" v-if="infoType == 0">
            <template v-slot="scope">
              <!-- 只在comment不为空时显示"去修改"按钮 -->
              <el-button link type="primary" size="small" v-if="scope.row.comment"
                @click="handleAddCommit(scope.row, 2)">
                修改评价
              </el-button>
            </template>
          </el-table-column>
          <!-- 学生自评 -->
          <el-table-column prop="evaluationText" label="学生自评" align="center">
            <template v-slot="scope">
              <span v-if="scope.row.evaluationText">{{ scope.row.evaluationText }}</span>
              <span v-if="!scope.row.evaluationText">学生暂未进行自我评价</span>
            </template>
          </el-table-column>
          <!-- 通过 or not -->
          <el-table-column prop="feedbackStatus" label="审核学生自评" align="center">
            <template v-slot="scope">
              <template v-if="scope.row.feedbackStatus == 'pending'">
                <el-button link type="primary" size="small" @click="access(scope.row)">通过</el-button>
                <el-button link type="primary" size="small" @click="Notaccess(scope.row)">不通过</el-button>
              </template>
              <template v-if="scope.row.feedbackStatus == 'approved'">
                <el-tag type="primary" size="small">已通过</el-tag>
              </template>
              <template v-if="scope.row.feedbackStatus == 'rejected'">
                <el-tag :type="'danger'" size="small">已打回</el-tag>
              </template>
              <template v-if="!scope.row.feedbackStatus">
                <el-tag type="primary" size="small">无操作</el-tag>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-col>
  </el-row>

  <!-- 修改评价的弹框 -->
  <el-dialog :title=title v-model="open" width="40%">
    <el-form ref="commentsRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="学号">
        <el-input v-model="form.studentid" :disabled="true" />
      </el-form-item>
      <el-form-item label="评价信息">
        <el-input v-model="form.comment" type="textarea" placeholder="请输入评价内容" rows="4" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="handlesubmitForm">提交</el-button>
    </div>
  </el-dialog>

  <!-- 新增评价的弹框 -->
  <el-dialog :title=title v-model="openadd" width="40%">
    <el-form ref="commentsAddRef" :model="addform" :rules="rulesadd" label-width="80px">
      <el-form-item label="学号">
        <el-select v-model="addform.studentid" placeholder="请选择学号">
          <!-- 这里假设 students 是你获取的学号列表 -->
          <el-option v-for="item in noCommontStudnetOptions" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="评价信息">
        <el-input v-model="addform.comment" type="textarea" placeholder="请输入评价内容" rows="4" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="handlesubmitFormAdd">提交</el-button>
    </div>
  </el-dialog>

</template>

<script setup name="Comments">
import { listComments, getComments, delComments, addComments, updateComments, listCommentsbyTeacher, listNoComments, StidentEvaluation, UpdateEvaluation } from "@/api/comments/comments";
import { listSeries } from "@/api/series/series";
// 查询基本信息
import { getInfo } from "@/api/login";
import { ref } from "vue";
const { proxy } = getCurrentInstance();
const { evaluate_time } = proxy.useDict('evaluate_time');
const Id = ref([])
const commentsList = ref([])
const open = ref(false);
const openadd = ref(false);
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
// 教师id
const teacherId = ref(null)
// 全部信息
const AllComments = ref([])
// 部分评价信息
const spareComment = ref([])
//为添加评价的同学
const noCommontStudnet = ref([])
//为添加评价的同学下拉框
const noCommontStudnetOptions = ref([])
// 当前下拉框选择的时间
const selectDate = ref([])

const data = reactive({
  form: {},
  addform: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentId: null,
  },
  rules: {
    comment: [
      { required: true, message: "评价不能为空", trigger: "blur" }
    ],
  },
  rulesadd: {
    comment: [
      { required: true, message: "评价不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules, addform, rulesadd } = toRefs(data);

/** 新增学生评价 */
function addComment() {
  title.value = "添加学生评价";
  reset();
  console.log(selectDate.value)
  if (selectDate.value === null || selectDate.value === undefined || selectDate.value === '' ||
    (typeof selectDate.value === 'object' && Object.keys(selectDate.value).length === 0)) {
    proxy.$modal.msgError("没有选择评价学期");
  } else {
    // 查询该老师名下的这个学期没有被评价的学生的信息
    listNoComments(teacherId.value, selectDate.value).then(response => {
      openadd.value = true;
      noCommontStudnet.value = response
      noCommontStudnetOptions.value = noCommontStudnet.value.map(item => {
        return {
          label: item.name,  // 显示的名称
          value: item.studentId // 对应的值
        }
      })
    });
  }

}

/** 新增学生评价 */
function handlesubmitFormAdd() {
  const studentId = addform.value.studentid
  // const student = noCommontStudnet.value.find(item => item.studentId === studentId)
  const comment = addform.value.comment
  addform.value = {
    teacherid: teacherId.value,
    studentid: studentId,
    statue: 0,
    comment: comment,
    createtime: new Date().toISOString(),
    commentTime: selectDate.value
  }
  addComments(addform.value).then(response => {
    if (response.code == 200) {
      openadd.value = false;
      proxy.$modal.msgSuccess("添加成功");
      getbasicMessage()
      reset()
    }
  })
}


/** 下拉框选择时触发函数*/
async function handleChange(selectedValue) {
  // 当前选择 selectedValue
  selectDate.value = selectedValue;
  // 过滤出符合条件的评论
  const temp = AllComments.value.filter(item => item.commentTime === selectedValue);
  const tempp = [];  // 用于存储更新后的数据

  // 使用 async/await 来确保异步操作完成
  for (let item of temp) {
    const { commentTime, studentid } = item;
    try {
      // 等待 StidentEvaluation 异步请求完成
      const res = await StidentEvaluation(studentid, commentTime);
      if (res.code === 200) {
        // 合并数据并推送到 tempp 数组
        tempp.push({ ...item, ...res.data });
      }
    } catch (error) {
      console.error("获取评估数据出错:", error);  // 错误处理
    }
  }

  // 所有数据获取完毕后更新 spareComment
  spareComment.value = tempp;
}

import { ElMessageBox } from 'element-plus';

function access(row) {
  const temp = {
    id: row.id,
    evaluationStatus: row.evaluationStatus,
    commentTime: row.commentTime,
    evaluationText: row.evaluationText,
    feedbackStatus: "approved",
    feedbackText: row.feedbackText,
    studentId: row.studentId,
    teacherId: row.teacherId
  };

  // 显示确认框
  ElMessageBox.confirm(
    '确定通过学生的自我评价信息吗?',
    '注意',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 用户点击"确定"按钮时执行的代码
      UpdateEvaluation(temp).then(response => {
        if (response.code == 200) {
          const time = selectDate.value
          handleChange(time)
        }
      })
    })
    .catch(() => {
      // 用户点击"取消"按钮时执行的代码
      console.log("User canceled the action");
    });
}


// 不通过
function Notaccess(row) {
  const temp = {
    id: row.id,
    evaluationStatus: row.evaluationStatus,
    commentTime: row.commentTime,
    evaluationText: row.evaluationText,
    feedbackStatus: "rejected",
    feedbackText: row.feedbackText,
    studentId: row.studentId,
    teacherId: row.teacherId
  };

  // 显示确认框
  ElMessageBox.confirm(
    '确定打回学生的自我评价信息吗?',
    '注意',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 用户点击"确定"按钮时执行的代码
      UpdateEvaluation(temp).then(response => {
        if (response.code == 200) {
          const time = selectDate.value
          handleChange(time)
        }
      })
    })
    .catch(() => {
      // 用户点击"取消"按钮时执行的代码
      console.log("User canceled the action");
    });
}
/** 查询当前老师信息 */
const infoType = ref(0);
function getbasicMessage() {
  AllComments.value = []
  spareComment.value = []
  getInfo().then(res => {
    const role = res.roles[0]
    if (role == "teacher") {
      teacherId.value = res.user.userName
      infoType.value = 0
      // 获取当前老师下的所有学生的评价信息
      listCommentsbyTeacher(teacherId.value).then(res => {
        console.log(selectDate.value);
        if (res.length > 0) {
          AllComments.value = res
          spareComment.value = res
        }
        if (selectDate.value.length) handleChange(selectDate.value)
      })
    } else if (role == "admin") {
      infoType.value = 1
      listComments().then(res => {
        if (res.code == 200) {
          AllComments.value = res.rows
          spareComment.value = res.rows
        }
      })
    }
  })
}


/** 查询学期评价列表 */
function getList() {
  loading.value = true;
  listComments(queryParams.value).then(response => {
    commentsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/**
 去评价功能
*/
function handleAddCommit(row, id) {
  if (id == 2) {
    title.value = "修改评价"
  }
  form.value = row
  form.value.statue = 0 //未看
  open.value = true;
}
// 取消按钮
function cancel() {
  open.value = false;
  openadd.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    commentId: null,
    teacherId: null,
    studentId: null,
    comment: null,
    createTime: null
  };
  addform.value = {}
  proxy.resetForm("commentsRef");
  proxy.resetForm("commentsAddRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 弹出框提交按钮 */
function handlesubmitForm() {
  proxy.$refs["commentsRef"].validate(valid => {
    if (valid) {
      updateComments(form.value).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        open.value = false;
        reset()
        getbasicMessage()
      });
    }
  });
}

getbasicMessage()

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.commentId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加学期评价";
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _commentId = row.commentId || ids.value
  getComments(_commentId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改学期评价";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["commentsRef"].validate(valid => {
    if (valid) {
      if (form.value.commentId != null) {
        updateComments(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        form.value.teacherId = Id.value
        // console.log(form.value)
        commentsList.value.forEach(item => {
          // console.log(item)
          if (item.studentId == form.value.studentId) {
            proxy.$modal.msgError("学生已评价")
          } else {
            addComments(form.value).then(response => {
              proxy.$modal.msgSuccess("新增成功");
              open.value = false;
              getList();
            });
          }
        })
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const _commentIds = row.commentId || ids.value;
  proxy.$modal.confirm('是否确认删除学期评价编号为"' + _commentIds + '"的数据项？').then(function () {
    return delComments(_commentIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('comments/comments/export', {
    ...queryParams.value
  }, `comments_${new Date().getTime()}.xlsx`)
}
</script>

<style scoped>
.grid-content {
  margin: 20px;
}

.grid-content label {
  margin-right: 10px;
}
</style>
